package com.yuanfengerp.customerexpenses.service.impl;

import com.yuanfengerp.customerexpenses.dao.ICustomerExpensesDao;
import com.yuanfengerp.customerexpenses.model.CustomerExpenseItemsInfo;
import com.yuanfengerp.customerexpenses.model.CustomerExpensesInfo;
import com.yuanfengerp.customerexpenses.service.ICustomerExpensesService;
import com.yuanfengerp.publicUtil.Result;
//import io.lettuce.core.dynamic.annotation.Param;
import com.yuanfengerp.publicUtil.SnowflakeIdWorker;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CustomerExpensesServiceImpl implements ICustomerExpensesService {
    @Autowired
    private ICustomerExpensesDao icem;

    @Override
    public Result<String> batchdelete(ArrayList<String> customer_expenses_IDs) {
        return null;
    }

    @Override
    public Result<String> batchreview(ArrayList<String> customer_expenses_IDs) {
        return null;
    }

    @Override
    public Result<String> deleteByPrimaryKey(String customer_expenses_ID) {
        if (icem.selectCustomerExpensesByPrimaryKey(customer_expenses_ID) == null)
            return Result.failure(500, "该数据不存在");
        int i = icem.deleteByPrimaryKey(customer_expenses_ID);
        return i > 0 ? Result.success("删除成功") : Result.failure(500, "删除失败");
    }

    @Override
    public Result<String> updateCustomerExpenses(CustomerExpensesInfo customerExpensesInfo) {
        if (icem.selectCustomerExpensesByPrimaryKey(customerExpensesInfo.getCustomer_expense_ID()) == null)
            return Result.failure(500, "该数据不存在");
        customerExpensesInfo.setCustomer_expenses_review_time(new Timestamp(System.currentTimeMillis()));
        int i = icem.updateCustomerExpenses(customerExpensesInfo);
        return i > 0 ? Result.success("修改成功") : Result.failure(500, "修改失败");
    }

    @Override
    public Result<String> insertCustomerExpenses(CustomerExpensesInfo customerExpensesInfo) {
        Double totalValue = 0.0;
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0);
        customerExpensesInfo.setCustomer_expense_ID(idWorker.nextId());
        customerExpensesInfo.setCustomer_expenses_operate_time(new Timestamp(System.currentTimeMillis()));
        customerExpensesInfo.setCustomer_expenses_state(0);
        customerExpensesInfo.setCustomer_expenses_review_time(new Timestamp(System.currentTimeMillis()));
        customerExpensesInfo.setCustomer_expenses_total_value(totalValue);
        // 插入供应商费用信息到数据库
        int i = icem.insertCustomerExpenses(customerExpensesInfo);
        if (i > 0) {
            // 如果插入成功，继续处理连表新增的费用项信息插入
            List<CustomerExpenseItemsInfo> customerExpenseItemsInfos = customerExpensesInfo.getCustomerExpenseItemsInfos();
            if (customerExpenseItemsInfos != null && !customerExpenseItemsInfos.isEmpty()) {
                for (CustomerExpenseItemsInfo customerExpenseItemsInfo : customerExpenseItemsInfos) {
                    Double value = customerExpenseItemsInfo.getValue();
                    totalValue += value;
                    customerExpenseItemsInfo.setCustomer_expense_ID(customerExpensesInfo.getCustomer_expense_ID());
                    int j = icem.insertCustomerExpensesItems(customerExpenseItemsInfo);
                    if (j <= 0) {
                        // 如果插入连接表失败，需要进行相应处理，这里简单返回失败结果
                        return Result.failure(500, "添加费用项到连接表失败");
                    }
                }
            }
            //保留小数点后两位
            DecimalFormat df = new DecimalFormat("#.00");
            String formattedValue = df.format(totalValue);
            double result = Double.parseDouble(formattedValue);
            customerExpensesInfo.setCustomer_expenses_total_value(result);
            int i1 = icem.insertCustomerExpenses(customerExpensesInfo);
            if (i1 <= 0)
                return Result.failure(500, "更新费用信息失败");
            // 如果所有操作都成功，返回成功结果
            return Result.success("添加成功");
        } else {
            // 如果插入失败，返回失败结果并附带错误信息
            return Result.failure(500, "添加失败，数据库插入操作未成功");
        }
    }

    @Override
    public Result<List<CustomerExpensesInfo>> selectAllCustomerExpenses(@Param("pageSize") Integer pageSize, @Param("pageNum") Integer pageNum) {
        Logger logger = LoggerFactory.getLogger(this.getClass());

        try {
            if (icem == null) {
                logger.error("ipmim is null");
                return Result.failure(500, "内部错误");
            }
            int totalRecords = icem.getTotalCount();
//            Integer pageNum = (Integer) params.get("pageNum");
//            Integer pageSize = (Integer) params.get("pageSize");
            // 获取总记录数，这里假设传入了合适的查询参数（如param1和param2）
            if (pageNum == null)
                pageNum = 5;
            if (pageSize == null)
                pageSize = 1;
            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalRecords / pageNum);

            // 判断页码是否超出范围
            if (pageSize > totalPages)
                return Result.failure(400, "页码超出有效范围");
            pageSize = (pageSize - 1) * pageNum;
            List<CustomerExpensesInfo> payMethodInfos = icem.selectAllCustomerExpenses(pageSize, pageNum);

            if (payMethodInfos != null) {
                logger.info("Successfully retrieved pay method info list");
                return Result.success(payMethodInfos);
            } else {
                logger.warn("No data found");
                return Result.failure(404, "没有数据");
            }
        } catch (Exception e) {
            logger.error("Error occurred while selecting all pay method info", e);
            return Result.failure(500, "内部错误");
        }
    }

    @Override
    public Result<List<CustomerExpensesInfo>> selectCustomerExpenses(Map<String, Object> params) {
        System.out.println(params.toString());
        params.put("pageNum", ((int) params.get("pageNum") - 1) * (int) params.get("pageSize"));
        List<CustomerExpensesInfo> list = icem.selectCustomerExpenses(params);
        if (list.isEmpty())
            return Result.failure(400, "没有数据");
        return Result.success(list);
    }


    @Override
    public Result<List<CustomerExpensesInfo>> selectCustomerExpensesItems(String customer_expenses_ID) {
        List<CustomerExpensesInfo> customerExpensesInfo = icem.selectCustomerExpensesItems(customer_expenses_ID);
        if (customerExpensesInfo == null)
            return null;
        return Result.success(customerExpensesInfo);
    }
}
